package com.hula.onion.book.server.spider.platforms.liyedai;

import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.JedisUtils;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.config.SysConstants;
import com.hula.onion.book.server.model.AccountInfo;
import com.hula.onion.book.server.utils.CookieUtils;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * Description:立业贷
 * Create Date:2018/1/30 19:33
 *
 * @author liangbing
 * @version 1.0
 */
@Component("liYeDaiSpider")
public class LiYeDaiSpider extends SpiderCommon {

    /**
     * 登录页面URL
     */
    private static final String LOGIN_PAGE_URL = "https://www.liyedai.cn/login";

    /**
     * 登录URL
     */
    private static final String LOGIN_URL = "https://www.liyedai.cn/front/logining";

    /**
     * setCode URL
     */
    private static final String SET_CODE_URL = "https://www.liyedai.cn/front/account/setCode";

    /**
     * 验证码URL
     */
    private static String CAPTCHA_URL = "https://www.liyedai.cn/front/account/getImg";

    /**
     * 获取账户信息URL
     */
    private static final String GET_ACCOUNT_INFO_URL = "https://www.liyedai.cn/front/account/homeOverview";

    @Autowired
    private LiYeDaiSpiderHelper liYeDaiSpiderHelper;

    /**
     * 执行爬取操作
     * 1.获取 RSA key
     * 2.组装模拟登陆参数，模拟登陆
     * 3.爬取用户详细信息
     */
    @Override
    public CommonResponse execute() {

        CommonResponse commonResponse;

        HttpClientContext httpContext = HttpClientContext.create();
        BasicCookieStore cookieStore = new BasicCookieStore();
        httpContext.setCookieStore(cookieStore);

        Map<String, Object> paraMap = liYeDaiSpiderHelper.installRequestParams(loginForm);

        //1. 从缓存中获取cookie，设置到cookie store中
        CookieUtils.setCookie(loginForm.getPlatformId(), loginForm.getUserId(), cookieStore);

        //模拟登陆
        String loginStr = HttpUtils.post(LOGIN_URL, paraMap, httpContext);

        logger.info("[LiYeDaiSpider] Http response result:{}", loginStr);

        //登陆成功
        if (StringUtils.isEmpty(loginStr)) {
            // 爬取数据
            String html = HttpUtils.get(GET_ACCOUNT_INFO_URL, httpContext);

            logger.info("[LiYeDaiSpider] Get account info result:{}", html);

            try {
                AccountInfo accountInfo = liYeDaiSpiderHelper.parseAccountBalance(html);

                commonResponse = new CommonResponse(ResponseStatusEnum.SUCCESS);
                commonResponse.setData(accountInfo);

            } catch (Exception e) {
                commonResponse = new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
            }

        } else {
            commonResponse = new CommonResponse(ResponseStatusEnum.ACCOUNT_ERROR);

            commonResponse.setMsg(loginStr);
        }

        return commonResponse;
    }

    @Override
    public String getCaptchaURL() {
        return CAPTCHA_URL;
    }

    @Override
    public String getLoginPageURL() {
        return LOGIN_PAGE_URL;
    }

    /**
     * 立业贷在获取验证码前获取一次code值
     */
    public void beforeGetImg(int platformId, String userFlag, HttpClientContext httpClientContext) {

        String jsonStr = HttpUtils.post(SET_CODE_URL, null, httpClientContext);

        if (!StringUtils.isEmpty(jsonStr)) {
            String code = JSONObject.parseObject(jsonStr).getString("img");
            CAPTCHA_URL = "https://www.liyedai.cn/front/account/getImg?id=" + code;

            //把code值存入缓存
            String key = SysConstants.REDIS_KEY_PRE + SysConstants.LYD_RANDOM_ID + platformId + ":" + userFlag;
            JedisUtils.getInstance().set(key, code);
        }

    }

}

